package com.example.statistics.common

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.RecyclerView
import com.example.statistics.R
import com.example.statistics.utils.Constants
import com.jhj.httplibrary.model.HttpParams
import com.jhj.slimadapter.SlimAdapter
import com.jhj.slimadapter.holder.ViewInjector
import com.jhj.slimadapter.itemdecoration.LineItemDecoration
import com.jhj.slimadapter.more.LoadMoreView
import com.example.statistics.ex.closeKeyboard
import com.example.statistics.ex.contentText
import com.example.statistics.ex.openKeyboard
import kotlinx.android.synthetic.main.activity_recyclerview_refresh.*
import kotlinx.android.synthetic.main.layout_empty_view.*
import kotlinx.android.synthetic.main.layout_search_bar.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.sdk27.coroutines.onTouch
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

abstract class BaseListActivity<T> : BaseActivity() {

    abstract val itemLayoutRes: Int

    lateinit var adapterLocal: SlimAdapter

    //var filterParams: HttpParams = HttpParams()


    //输入搜索
    open val inputSearch = false

    //输入搜索提示
    open val inputSearchHint = "输入搜索内容"

    //
    open val inputSearchClickHint = "点击搜索"

    //分割线
    open val hasSplitLine = true

    var filterParams: HttpParams = HttpParams()

    val mRecyclerView: RecyclerView
        get() = recyclerView

    val ivFilter: ImageView
        get() = iv_search_filter

    val ivOther: ImageView
        get() = iv_search_other

    var dataList: MutableList<T> = mutableListOf()
        set(value) {
            field = formatList(value.toMutableList())
            dataListEmpty(field)
        }

    fun dataListEmpty(value: List<T>) {
        if (value.isEmpty()) {
            include_empty_view.visibility = View.VISIBLE
            tv_refresh_reason.text = "暂无数据"
        } else {
            include_empty_view.visibility = View.GONE
        }
        adapterLocal.setDataList(value)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recyclerview_refresh)
        initAdapter()
        initDrawerLayout()
        include_empty_view.onClick {
            refresh()
        }
        //输入搜索
        if (inputSearch) {
            inputSearch()
            val search = intent.getStringExtra(Constants.SEARCH)
            tv_search_click.text = inputSearchClickHint
            et_search_input.hint = inputSearchHint
            layout_search_bar.visibility = View.VISIBLE
            et_search_input.contentText = search.orEmpty()
            if (search.isNullOrBlank()) refresh()
        } else {
            layout_search_bar.visibility = View.GONE
            refresh()
        }

    }


    private fun initAdapter() {
        if (hasSplitLine)
            recyclerView.addItemDecoration(LineItemDecoration())
        recyclerView.onTouch { v, event ->
            v.closeKeyboard()
            if (et_search_input.text.isNullOrBlank()) {
                layout_search_mark.visibility = View.VISIBLE
            }
        }

        adapterLocal = SlimAdapter.creator()
                .setGenericActualType(genericType())
                .register<T>(itemLayoutRes) { injector, bean, position ->
                    itemViewConvert(this, injector, bean, position)
                }
                .attachTo(recyclerView)
                .setLoadMoreView(object : LoadMoreView() {
                    override val layoutId: Int
                        get() = R.layout.list_item_load_more
                    override val loadEndViewId: Int
                        get() = R.id.load_more_load_end_view
                    override val loadFailViewId: Int
                        get() = R.id.load_more_load_fail_view
                    override val loadingViewId: Int
                        get() = R.id.load_more_loading_view
                })
    }


    private fun initDrawerLayout() {
        //设置抽屉模式
        drawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
        drawer_layout.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerStateChanged(p0: Int) {
            }

            override fun onDrawerSlide(p0: View, p1: Float) {
                drawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
            }

            override fun onDrawerClosed(p0: View) {
                drawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
            }

            override fun onDrawerOpened(p0: View) {

            }
        })
    }

    /**
     *
     */
    fun initDrawerLayout(layoutRes: Int, body: (View, DrawerLayout) -> Unit) {

        //点击筛选按钮
        iv_search_filter.visibility = View.VISIBLE
        iv_search_filter.onClick {
            iv_search_filter.closeKeyboard()
            if (!drawer_layout.isDrawerOpen(Gravity.RIGHT)) {
                drawer_layout.openDrawer(Gravity.RIGHT)
            } else {
                drawer_layout.closeDrawer(Gravity.RIGHT)
            }
        }

        //自定义筛选界面
        val view = LayoutInflater.from(this).inflate(layoutRes, layout_right_drawer, false)
        layout_right_drawer.addView(view)
        body(view, drawer_layout)

        //
        layout_operate.setOnRejectListener {
            filterParams.clear()
            resetFilter(view)
            drawer_layout.closeDrawer(Gravity.RIGHT)
            refresh()
        }
        layout_operate.setOnCommitListener {
            filterParams.clear()
            filter()
            drawer_layout.closeDrawer(Gravity.RIGHT)
            refresh()
        }
    }


    /**
     * 筛选
     */
    open fun filter() {}

    /**
     * 重置
     */
    open fun resetFilter(view: View) {}


    /**
     * 输入搜索
     */
    private fun inputSearch() {
        var repeatStr: String? = ""
        layout_search_mark.onTouch { _, _ ->
            layout_search_mark.visibility = View.GONE
            et_search_input.openKeyboard()
        }

        //输入搜索
        et_search_input.addTextChangedListener(object : TextWatcher {

            override fun afterTextChanged(p0: Editable?) {
                if (p0?.length != 0) {
                    layout_search_mark.visibility = View.GONE
                } else {
                    layout_search_mark.visibility = View.VISIBLE
                }
                val searchText: String? = p0?.toString()
                if (searchText == repeatStr) { //避免多次调用
                    return
                }
                repeatStr = searchText
                inputSearch(searchText)
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }
        })
    }


    /**
     * 获取泛参数实际类型
     */
    open fun genericType(): Type {
        //获取当前类带有泛型的父类
        val clazz: Type? = this.javaClass.genericSuperclass
        return if (clazz is ParameterizedType) {
            //获取父类的泛型参数（参数可能有多个，获取第一个）
            clazz.actualTypeArguments[0]
        } else {
            throw IllegalArgumentException()
        }
    }


    abstract fun refresh()
    abstract fun inputSearch(search: String?)
    abstract fun itemViewConvert(adapter: SlimAdapter, injector: ViewInjector, bean: T, position: Int)


    open fun formatList(dataList: MutableList<T>): MutableList<T> {
        return dataList
    }
}